<?php

namespace App\Http\Controllers\Company;

use App\Exceptions\ApiException;
use App\Http\Requests\BasicRequest;
use App\Http\Requests\DutyStartRequest;
use App\Models\ClientUser;
use App\Models\ClientUserManagerDuty;
use App\Models\ClientUserRelationship;
use App\Models\DutyBudding;
use App\Models\HouseDistrict;
use App\Models\ClientUserWorking;
use Illuminate\Support\Facades\DB;

class DutyController extends CommonController
{
     private  $uid_in;
     private  $uid_select;
     public function __construct(){
          parent::__construct();
          $uid_in = ClientUserRelationship::treeChildrenOne($this->ship->uid,$this->ship->type);
          $uid_in->prepend(ClientUser::select(['id as uid', 'realname'])->find($this->uid));
          $this->uid_select = $uid_in;
          $this->uid_in= $uid_in->pluck('uid')->toArray();
     }

     //获取房屋信息与值班状态
	 public function index(){
         $check = ClientUserWorking::where(['uid'=>$this->uid,'status'=>1])->first();
         $h = $this->_getworkarea();
         if($check){
             //如果值班
            $budding = DutyBudding::where(['uid'=>$this->uid,'status'=>1])->select('budding_id')->get();
            $budding = $budding->implode('budding_id', ',');
            $working = 1;
         }else{
             $budding = '';
             $working = 0;
         }
         $house = HouseDistrict::select('id as house_id','type','name')->where('id',$h->house_id)->first();
         $house_ids =[];

         switch ($house->type) {
             case 7:
                 $house2 = HouseDistrict::select('id as house_id','parent_id','name')->where(['parent_id' => $house->house_id])->get();
                 foreach ($house2 as $v) {
                     $house_ids[] = ['house_id'=>$v->house_id,'name'=>$v->name];
                 }
                 break;
             case 3:
                 $house_ids[] = ['house_id'=>$house->house_id,'name'=>$house->name];
                 break;
             case 2:
                 $house2 = HouseDistrict::select('id as house_id','type','parent_id','name')->where(['parent_id' => $house->house_id])->get();
                 foreach ($house2 as $v) {
                     $house3 = HouseDistrict::select('id as house_id','type','parent_id','name')->where(['parent_id' => $v->house_id])->get();
                     $d = [];
                     foreach ($house3 as $vv) {
                         $d[] = array(
                             'house_id'=>$vv->house_id,
                             'name'=>$vv->name_long,
                         );
                     }
                     $house_ids = array_merge($house_ids,$d);
                 }
                 break;
         }

         $return  = [
             'working' => $working,
             'house' => $house_ids,
             'budding' => $budding,
             'name'  => $this->user->realname,
             'avatar' => $this->user->avatar,
         ];
         return json_success('OK', $return);
     }

	/**
	 * @param BasicRequest $request
	 * @return array
	 * 开始值班
	 */
	public function start(DutyStartRequest $request)
	{
	    $budding = $request->input('budding');
        $UserWorking = ClientUserWorking::select('id')->where(['uid'=>$this->uid,'status'=>1])->first();
        if($UserWorking) {
            return json_success('ok', ['isworking' => $UserWorking->id ? 1 : 0]); //1值班 0未值班
        }
        $h = $this->_getworkarea();

        $house_id = is_numeric($h->house_id) ? [$h->house_id] : explode(',', $h->house_id);
        $house = HouseDistrict::select('id','type','parent_id')->whereIn('id',$house_id)->first();
        switch ($house->type) {
            case 7:
                break;
            case 3:
                $house = HouseDistrict::select('id','type','parent_id')->where(['id' => $house->parent_id])->first();
                break;
            case 2:
                $house = HouseDistrict::select('id','type','parent_id')->where(['parent_id' => $house->id])->first();
                break;
        }
        if($house->type !=7 )
            return json_error('fail','您不符合值班条件');
        //添加值班记录
        $house_id = $house->id;
        DB::transaction(function () use($house_id,$budding) {
            $duty=array(
                'uid'=>$this->uid,
                'house_id'=>$house_id,
                'status'=>1
            );
            $duty_id = ClientUserWorking::create($duty)->id ;
            $buddings = explode(',',$budding);
            foreach ($buddings as $k =>$v) {
                $duty_budding = array(
                    'uid' => $this->uid,
                    'house_id' => $house_id,
                    'status' => 1,
                    'budding_id' => $v,
                    'duty_id' => $duty_id,
                );
                //处理其他管家
                $managers = DutyBudding::where(['status'=>1,'budding_id'=>$v])->value('uid');
                DutyBudding::where(['status'=>1,'budding_id'=>$v])->update(['status'=>0]);
                $managers_count=DutyBudding::where(['uid'=>$managers])->count();
                if($managers_count<=0){
                    //如果管家没有值班的楼栋，则结束值班
                    ClientUserManagerDuty::where(['uid'=>$managers,'date'=>date('Y-m-d'),'status'=>1])->update(['end_time'=>time(),'status'=>0]);
                }
                DutyBudding::create($duty_budding);
            }
        });

        // 插入值班记录 和值班开始时间
        $data = [
            'uid'=>$this->uid,
            'start_time'=>time(),
            'status'=>1,
            'date'=>date('Y-m-d'),
        ];
        ClientUserManagerDuty::create($data);
        return json_success('ok',['isworking'=>1]);
	}



	private function _getworkarea(){
		return ClientUser::select(DB::raw('client_user_relationship.house_id,client_user_relationship.village_id')) 
			->leftJoin('client_user_roles','client_user.id','=','client_user_roles.uid')
			->leftJoin('client_user_relationship','client_user_roles.ship_id','=','client_user_relationship.id')
			->where('client_user.id','=',$this->uid)
			->first();
	}
}